package com.bocloud.cmp.driver.providers.jd;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.providers.ServerDriver;
import com.bocloud.cmp.model.OSMigrateModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.model.SnapshotModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jcloud.cap.client.ClientConfig;
import com.jcloud.cap.client.IClient;
import com.jcloud.cap.client.JCloudClient;
import com.jcloud.cap.client.builder.v1.CreateServerRequestBuilder;
import com.jcloud.cap.client.builder.v1.DeleteServerRequestBuilder;
import com.jcloud.cap.client.builder.v1.QuerySecurityGroupsRequestBuilder;
import com.jcloud.cap.client.builder.v1.QueryServerDetailRequestBuilder;
import com.jcloud.cap.client.builder.v1.QueryServersRequestBuilder;
import com.jcloud.cap.client.builder.v1.RestartServerRequestBuilder;
import com.jcloud.cap.client.builder.v1.StartServerRequestBuilder;
import com.jcloud.cap.client.builder.v1.StopServerRequestBuilder;
import com.jcloud.cap.client.exception.ClientException;
import com.jcloud.cap.client.exception.ServerException;
import com.jcloud.cap.client.http.HttpConfig;
import com.jcloud.cap.data.model.v1.CreateServerRequest;
import com.jcloud.cap.data.model.v1.CreateServerResponse;
import com.jcloud.cap.data.model.v1.DeleteServerResponse;
import com.jcloud.cap.data.model.v1.QuerySecurityGroupsResponse;
import com.jcloud.cap.data.model.v1.QueryServerDetailResponse;
import com.jcloud.cap.data.model.v1.QueryServersResponse;
import com.jcloud.cap.data.model.v1.QueryServersResponse.Server;
import com.jcloud.cap.data.model.v1.RestartServerResponse;
import com.jcloud.cap.data.model.v1.SecurityGroupResponse.SecurityGroup;
import com.jcloud.cap.data.model.v1.StartServerResponse;
import com.jcloud.cap.data.model.v1.StopServerResponse;

public class JdServerDriver extends JdDriver implements ServerDriver {
	private static Logger logger = LoggerFactory.getLogger(JdServerDriver.class);
	private IClient client;

	/**
	 * @param accessKey
	 * @param secretKey
	 * @param endpoint
	 */
	public JdServerDriver(String accessKey, String secretKey, String endpoint, String region) {
		super(accessKey, secretKey, endpoint, region);
		ClientConfig config = new ClientConfig();
		HttpConfig httpConfig = new HttpConfig();
		// 调用地址
		httpConfig.setEndpoint(endpoint);
		httpConfig.setReadTimeout(20000);
		httpConfig.setConnectTimeout(20000);
		config.setHttpConfig(httpConfig);
		config.setCredential(this.getCredential().getCapCredential());
		client = new JCloudClient(config);
	}

	@Override
	public BsmResult create(ServerModel server) {
		CreateServerRequestBuilder builder = CreateServerRequestBuilder.create();
		this.init(builder, "compute", "createServer", this.getRegion());
		CreateServerRequest request = builder.imageId(server.getImageId()).cpu(server.getCpu())
				.memory(server.getMemory()).subnetId(server.getSubnetId()).serverName(server.getName())
				.userPassword(server.getPassword()).description(server.getRemark()).count(server.getCount()).feeType(1)
				.build();
		// request.setAccount("jcloudtactic"); // 此处须传入账号名;
		try {
			CreateServerResponse response = client.send(request);
			return detail(server.getName(), response.getRequestId());
		} catch (ClientException | ServerException e) {
			logger.error("Create server [{}] exception!", e);
			return new BsmResult(false, "Create server failed");
		}
	}

	@Override
	public BsmResult start(String instanceId) {
		StartServerRequestBuilder builder = StartServerRequestBuilder.create();
		this.init(builder, "compute", "startServer", this.getRegion());
		try {
			StartServerResponse response = client.send(builder.serverId(instanceId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Start server [{}] exception!", e);
			return new BsmResult(false, "Start server failed");
		}
	}

	@Override
	public BsmResult stop(String instanceId) {
		StopServerRequestBuilder builder = StopServerRequestBuilder.create();
		this.init(builder, "compute", "stopServer", this.getRegion());
		try {
			StopServerResponse response = client.send(builder.serverId(instanceId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Stop server [{}] exception!", e);
			return new BsmResult(false, "Stop server failed");
		}
	}

	@Override
	public BsmResult reboot(String instanceId) {
		RestartServerRequestBuilder builder = RestartServerRequestBuilder.create();
		this.init(builder, "compute", "restartServer", this.getRegion());
		try {
			RestartServerResponse response = client.send(builder.serverId(instanceId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Restart server [{}] exception!", e);
			return new BsmResult(false, "Restart server failed");
		}
	}

	@Override
	public BsmResult remove(String instanceId) {
		DeleteServerRequestBuilder builder = DeleteServerRequestBuilder.create();
		this.init(builder, "compute", "deleteServer", this.getRegion());
		try {
			DeleteServerResponse response = client.send(builder.serverId(instanceId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Remove server [{}] exception!", e);
			return new BsmResult(false, "Remove server failed");
		}
	}

	@Override
	public BsmResult list() {
		QueryServersRequestBuilder builder = QueryServersRequestBuilder.create();
		init(builder, "compute", "queryServers ", this.getRegion());
		try {
			QueryServersResponse response = client.send(builder.pageNumber(1).pageSize(100).build());
			List<Server> servers = response.getServers();
			List<ServerModel> models = Lists.newArrayList();
			if (null != servers && !servers.isEmpty()) {
				// 虚机详细
				QueryServerDetailRequestBuilder detailBuilder = QueryServerDetailRequestBuilder.create();
				init(detailBuilder, "compute", "queryServerDetail ", this.getRegion());
				// 安全组map
				Map<String, String> map = Maps.newHashMap();
				QuerySecurityGroupsRequestBuilder groupBuilder = QuerySecurityGroupsRequestBuilder.create();
				this.init(groupBuilder, "network", "querySecurityGroups", this.getRegion());
				QuerySecurityGroupsResponse groupResponse = client.send(groupBuilder.build());
				List<SecurityGroup> gourps = groupResponse.getSecurityGroups();
				for (SecurityGroup group : gourps) {
					map.put(group.getName(), group.getSecurityGroupId());
				}
				for (Server server : servers) {
					QueryServerDetailResponse detailResponse = client
							.send(detailBuilder.serverId(server.getServerId()).build());
					ServerModel model = new ServerModel(server.getServerId(), server.getServerName(),
							detailResponse.getDescription(), server.getCreateTime(), server.getFixIp(),
							server.getFloatingIp(), detailResponse.getStatus(), server.getCpu(), server.getMemory(),
							server.getDisk(), detailResponse.getImageId(), detailResponse.getSubnetId(),
							detailResponse.getRouterId(), detailResponse.getNetworkId(),
							map.get(detailResponse.getSecurityGroupName()), null);
					models.add(model);
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException | ServerException e) {
			logger.error("List server [{}] exception!", e);
			return new BsmResult(false, "List server failed");
		}
	}

	@Override
	public BsmResult detail(String instanceId) {
		QueryServersRequestBuilder builder = QueryServersRequestBuilder.create();
		init(builder, "compute", "queryServers ", this.getRegion());
		try {
			QueryServersResponse response = client.send(builder.pageNumber(1).pageSize(100).build());
			List<Server> servers = response.getServers();
			ServerModel model = null;
			if (null != servers && !servers.isEmpty()) {
				for (Server server : servers) {
					if (server.getServerId().equals(instanceId)) {
						// 虚机详细
						QueryServerDetailRequestBuilder detailBuilder = QueryServerDetailRequestBuilder.create();
						init(detailBuilder, "compute", "queryServerDetail ", this.getRegion());
						// 安全组map
						Map<String, String> map = Maps.newHashMap();
						QuerySecurityGroupsRequestBuilder groupBuilder = QuerySecurityGroupsRequestBuilder.create();
						this.init(groupBuilder, "network", "querySecurityGroups", this.getRegion());
						QuerySecurityGroupsResponse groupResponse = client.send(groupBuilder.build());
						List<SecurityGroup> gourps = groupResponse.getSecurityGroups();
						for (SecurityGroup group : gourps) {
							map.put(group.getName(), group.getSecurityGroupId());
						}
						QueryServerDetailResponse detailResponse = client
								.send(detailBuilder.serverId(server.getServerId()).build());
						model = new ServerModel(server.getServerId(), server.getServerName(),
								detailResponse.getDescription(), server.getCreateTime(), server.getFixIp(),
								server.getFloatingIp(), detailResponse.getStatus(), server.getCpu(), server.getMemory(),
								server.getDisk(), detailResponse.getImageId(), detailResponse.getSubnetId(),
								detailResponse.getRouterId(), detailResponse.getNetworkId(),
								map.get(detailResponse.getSecurityGroupName()), null);
					}
				}
			}
			if (null == model) {
				return new BsmResult(false, "该对象不存在");
			}
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query server [{}] exception!", e);
			return new BsmResult(false, "Query server failed");
		}
	}

	private BsmResult detail(String name, String requestId) {
		QueryServersRequestBuilder builder = QueryServersRequestBuilder.create();
		init(builder, "compute", "queryServers ", this.getRegion());
		try {
			QueryServersResponse response = client.send(builder.pageNumber(1).pageSize(100).build());
			List<Server> servers = response.getServers();
			ServerModel model = null;
			if (null != servers && !servers.isEmpty()) {
				for (Server server : servers) {
					if (server.getServerName().equals(name)) {
						// 虚机详细
						QueryServerDetailRequestBuilder detailBuilder = QueryServerDetailRequestBuilder.create();
						init(detailBuilder, "compute", "queryServerDetail ", this.getRegion());
						// 安全组map
						Map<String, String> map = Maps.newHashMap();
						QuerySecurityGroupsRequestBuilder groupBuilder = QuerySecurityGroupsRequestBuilder.create();
						this.init(groupBuilder, "network", "querySecurityGroups", this.getRegion());
						QuerySecurityGroupsResponse groupResponse = client.send(groupBuilder.build());
						List<SecurityGroup> gourps = groupResponse.getSecurityGroups();
						for (SecurityGroup group : gourps) {
							map.put(group.getName(), group.getSecurityGroupId());
						}
						QueryServerDetailResponse detailResponse = client
								.send(detailBuilder.serverId(server.getServerId()).build());
						model = new ServerModel(server.getServerId(), server.getServerName(),
								detailResponse.getDescription(), server.getCreateTime(), server.getFixIp(),
								server.getFloatingIp(), detailResponse.getStatus(), server.getCpu(), server.getMemory(),
								server.getDisk(), detailResponse.getImageId(), detailResponse.getSubnetId(),
								detailResponse.getRouterId(), detailResponse.getNetworkId(),
								map.get(detailResponse.getSecurityGroupName()), requestId);
					}
				}
			}
			if (null == model) {
				return new BsmResult(false, "该对象不存在");
			}
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query server [{}] exception!", e);
			return new BsmResult(false, "Query server failed");
		}
	}

	@Override
	public BsmResult joinSGroup(String instanceId, String groupId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult leaveSGroup(String instanceId, String groupId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult modify(ServerModel server) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult migrate(ServerModel server) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult OSMigrate(OSMigrateModel OSMigrate) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult snapshot(SnapshotModel snapshotModel) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult suspend(String instanceId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult VncConsole(String vncType, String serverId) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public BsmResult resume(String instanceId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BsmResult unpause(String instanceId) {
        // TODO Auto-generated method stub
        return null;
    }
}
